<?php
import("ORG.Util.Function");
import("@.Org.Utils");
import("@.Org.SnatchTool");
import("@.Org.CommonTool");


class SnatchAction extends CommonAction{	
	
	public function _initialize(){
		parent::_initialize();				
		$param           =    $this->_get('_URL_');
		$controller      =    $param[0];
		$action          =    $param[1];		
		//language
		$lang            =    L($action);  		
		$manage          =    L('manage');
		
		$this->assign("manage",$manage);
		$this->assign("current",$lang);
		$this->assign("lang",$lang);
	}
	
	public function _empty(){
		t('空操作');
	}
	
	/**
	 * 夺宝奇兵,抢购
	 * Enter description here ...
	 */
	public function snatch_list(){
	
	    $sql_snatchs 		= 	get_sql_snatchlist();	
	    $sort_flag  		= 	sort_flag($snatchs['filter']);
	    $this->assign($sort_flag['tag'], $sort_flag['img']);		
	    
	    $param 				= 	array(
			'result'	=> $sql_snatchs,					//分页用的数组或sql
			'listvar'	=> 'snatch_list',						//分页循环变量
			'listRows'	=> 20,								//每页记录数
			'parameter'	=> 'cat_id=' . $cat_id . "&intro_type=" . $intro_type . "&invalid=" . $invalid,//url分页后继续带的参数
			'target'	=> 'content',	    				//ajax更新内容的容器id，不带#
			'pagesId'	=> 'page',							//分页后页的容器id不带# target和pagesId同时定义才Ajax分页
			'template'	=> 'User:msg_list',				//ajax更新模板
		);	    
	    
		$this->page_snatch_list($param);
		$this->display();
	}
	
	/**
	 * 夺宝奇兵分页
	 * Enter description here ...
	 */
	public function page_snatch_list($param){		
		extract($param);
		//总记录数
		$flag 		= 	is_string($result);
		
		$listvar 	= 	$listvar ? $listvar : 'list';
		$listRows 	= 	$listRows? $listRows : 21;
		if ($flag){
			$totalRows	=	count(M()->query($result));
		}			
		else{
			$totalRows = ($result) ? count($result) : 1;
		}
		//创建分页对象
		if ($target && $pagesId)
			$p = new Page($totalRows, $listRows, $parameter, $url,$target, $pagesId);
		else
			$p = new Page($totalRows, $listRows, $parameter,$url);
		//抽取数据
		if ($flag) {
			$result .= " LIMIT {$p->firstRow},{$p->listRows}";
			$voList = M()->query($result);
		} else {
			$voList = array_slice($result, $p->firstRow, $p->listRows);
		}
		$pages = C('PAGE');//要ajax分页配置PAGE中必须theme带%ajax%，其他字符串替换统一在配置文件中设置，
		// 格式化数据
	    foreach ($voList AS $key => $val){
        	$voList[$key]['start_time'] 		= 	local_date($GLOBALS['_CFG']['time_format'], $val['start_time']);
        	$voList[$key]['end_time']   		= 	local_date($GLOBALS['_CFG']['time_format'], $val['end_time']);
        	$info = unserialize($voList[$key]['ext_info']);
        	unset($voList[$key]['ext_info']);
        	if ($info){
	            foreach ($info as $info_key => $info_val){
	                $voList[$key][$info_key] 	= 	$info_val;
            	}
        	}
    	}
    	
		//可以使用该方法前用C临时改变配置
		foreach ($pages as $key => $value) {
			$p->setConfig($key, $value); // 'theme'=>'%upPage% %linkPage% %downPage% %ajax%'; 要带 %ajax%
		}
		//分页显示
		$page = $p->show();		
		//模板赋值
		$this->assign($listvar, $voList);
		$this->assign("page", $page);
		if ($this->isAjax()) {//判断ajax请求
			layout(false);
			$template = (!$template) ? 'ajaxlist' : $template;
			exit($this->fetch($template));
		}
		return $voList;		
	}	
	
	/**
	 * 查看夺宝奇兵(抢购活动)详细信息
	 * Enter description here ...
	 */
	public function view_snatch(){
	
	    $id 				= 	empty($_REQUEST['snatch_id']) ? 0 : intval($_REQUEST['snatch_id']);	
	   	
	    $sort_flag  		= 	sort_flag($bid_list['filter']);
	    $this->assign($sort_flag['tag'], $sort_flag['img']);
	    /* 赋值 */
	    $this->assign('info',         get_snatch_info($id));	    
	    $this->assign('result',       get_snatch_result($id));
	    ///////////////// 查看夺宝奇兵的操作详细信息
	    $sql_bid_list 		= 	get_sql_snatch_detail();
	    
	    $param 				= 	array(
			'result'	=> $sql_bid_list,					//分页用的数组或sql
			'listvar'	=> 'bid_list',						//分页循环变量
			'listRows'	=> 20,								//每页记录数
			'parameter'	=> 'cat_id=' . $cat_id . "&intro_type=" . $intro_type . "&invalid=" . $invalid,//url分页后继续带的参数
			'target'	=> 'content',	    				//ajax更新内容的容器id，不带#
			'pagesId'	=> 'page',							//分页后页的容器id不带# target和pagesId同时定义才Ajax分页
			'template'	=> 'Snatch:snatch_view',				//ajax更新模板
		);	    
		extract($param);
		//总记录数
		$flag = is_string($result);
		
		$listvar = $listvar ? $listvar : 'list';
		$listRows = $listRows? $listRows : 21;
		if ($flag){
			$totalRows	=	count(M()->query($result));
		}			
		else{
			$totalRows = ($result) ? count($result) : 1;
		}
		//创建分页对象
		if ($target && $pagesId)
			$p = new Page($totalRows, $listRows, $parameter, $url,$target, $pagesId);
		else
			$p = new Page($totalRows, $listRows, $parameter,$url);
		//抽取数据
		if ($flag) {
			$result .= " LIMIT {$p->firstRow},{$p->listRows}";
			$voList = M()->query($result);
		} else {
			$voList = array_slice($result, $p->firstRow, $p->listRows);
		}
		$pages = C('PAGE');//要ajax分页配置PAGE中必须theme带%ajax%，其他字符串替换统一在配置文件中设置，
		// 格式化数据
	    foreach ($voList AS $key => $val){
    	    $voList[$key]['bid_time'] 	= 	date($GLOBALS['_CFG']['time_format'], $val['bid_time']);
    	}	
		
		//可以使用该方法前用C临时改变配置
		foreach ($pages as $key => $value) {
			$p->setConfig($key, $value); // 'theme'=>'%upPage% %linkPage% %downPage% %ajax%'; 要带 %ajax%
		}
		//分页显示
		$page = $p->show();		
		//模板赋值
		$this->assign($listvar, $voList);
		$this->assign("page", $page);
		if ($this->isAjax()) {//判断ajax请求
			layout(false);
			$template = (!$template) ? 'ajaxlist' : $template;
			exit($this->fetch($template));
		}
	    ///////////////// 查看夺宝奇兵的操作详细信息
	    	    
	    $this->display('snatch_view');
	}	
	
	
	
	
	
	/**
	 * 添加抢购活动(活动里面包括商品)
	 * Enter description here ...
	 */
	public function add_snatch(){
	
		$GoodsModel		=	new GoodsModel();
				
	    /* 初始化信息 */
	    $start_time 	= 	local_date('Y-m-d H:i');
	    $end_time   	= 	local_date('Y-m-d H:i', strtotime('+1 week'));
	    $snatch     	= 	array(
	    	'start_price'=>'1.00',
	    	'end_price'=>'800.00',
	    	'max_price'=>'0', 
	    	'cost_points'=>'1',
	    	'start_time' => $start_time,
	    	'end_time' => $end_time,
	    	'option'=>'<option value="0">'. L('make_option') .'</option>'
	   	);
		
	    $this->assign('snatch',       $snatch);
	    $this->assign('cat_list',     $GoodsModel->cat_list()); // 商品分类
	    $this->assign('brand_list',   get_brand_list());		// 品牌列表
	    $this->assign('form_action',  'insert');
	    $this->assign('action',  	  'add_snatch_ok');
	    
		$this->display('snatch_info');
	}
	
	/**
	 * 处理添加夺宝奇兵(抢购活动)
	 * Enter description here ...
	 */
	public function add_snatch_ok(){
		
		$CommonModel		=	new CommonModel();
		
	    /* 检查商品是否存在 */
	    $sql 				= 	"SELECT goods_name FROM " . 'ybr_goods' . " WHERE goods_id = '$_POST[goods_id]'";
	    $_POST['goods_name']= 	$CommonModel->getOne($sql);
	    if (empty($_POST['goods_name'])){
	        $this->error(L('no_goods'));
	    }
	
	    $sql 		=	"SELECT COUNT(*) ".
	           			" FROM " . 'ybr_goods_activity' .
	           			" WHERE act_type='" . GAT_SNATCH . "' AND act_name='" . $_POST['snatch_name'] . "'" ;
	    if ($CommonModel->getOne($sql)){
	        //sys_msg(sprintf($_LANG['snatch_name_exist'],  $_POST['snatch_name']) , 1);
	        $this->error(sprintf(L('snatch_name_exist'),  $_POST['snatch_name']));
	    }
	
	    /* 将时间转换成整数 */
	    $_POST['start_time'] = 	local_strtotime($_POST['start_time']);
	    $_POST['end_time']   = 	local_strtotime($_POST['end_time']);
	
	    /* 处理提交数据 */
	    if (empty($_POST['start_price'])){
	        $_POST['start_price'] = 0;
	    }
	    if (empty($_POST['end_price'])){
	        $_POST['end_price'] = 0;
	    }
	    if (empty($_POST['max_price'])){
	        $_POST['max_price'] = 0;
	    }
	    if (empty($_POST['cost_points'])){
	        $_POST['cost_points'] = 0;
	    }
	    if (isset($_POST['product_id']) && empty($_POST['product_id'])){
	        $_POST['product_id'] = 0;
	    }
	
	    $info 			= 	array('start_price'=>$_POST['start_price'], 'end_price'=>$_POST['end_price'], 'max_price'=>$_POST['max_price'], 'cost_points'=>$_POST['cost_points']);
	
	    /* 插入数据 */
	    $record 		= 	array('act_name'=>$_POST['snatch_name'], 'act_desc'=>$_POST['desc'],
	                    		'act_type'=>GAT_SNATCH, 'goods_id'=>$_POST['goods_id'], 'goods_name'=>$_POST['goods_name'],
	                    		'start_time'=>$_POST['start_time'], 'end_time'=>$_POST['end_time'],
	                    		'product_id'=>$_POST['product_id'],
	                    		'is_finished'=>0, 'ext_info'=>serialize($info)
	   	);
	    $CommonModel->AutoExecute('goods_activity',$record,'INSERT');	
	    admin_log($_POST['snatch_name'],'add','snatch'); // 记录操作	    
	    $this->success(L('add_succeed'),U('snatch/add_snatch'));		
	}	
		
	/**
	 * 修改(夺宝奇兵)抢购活动信息
	 * Enter description here ...
	 */
	public function mod_snatch(){
	
	    $snatch        		= 	get_snatch_info($_REQUEST['id']);
	    $snatch['option'] 	= 	'<option value="' . $snatch['goods_id'].'">' . $snatch['goods_name'] . '</option>';
	    
	    $this->assign('snatch',             $snatch);
	    $this->assign('form_action',        'update');
	    $this->assign('action',        		'mod_snatch_ok');
		    
	    /* 商品货品表 */
	    $this->assign('good_products_select', get_good_products_select($snatch['goods_id']));	    
		$this->display('snatch_info');
	}
	
	/**
	 * 处理修改(夺宝奇兵)抢购活动信息
	 * Enter description here ...
	 */
	public function mod_snatch_ok(){
		
		$CommonModel			=	new CommonModel();
	    /* 将时间转换成整数 */
	    $_POST['start_time'] 	= 	local_strtotime($_POST['start_time']);
	    $_POST['end_time']  	= 	local_strtotime($_POST['end_time']);
	
	    /* 处理提交数据 */
	    if (empty($_POST['snatch_name'])){
	        $_POST['snatch_name'] = '';
	    }
	    
	    if (empty($_POST['goods_id'])){
	        $_POST['goods_id'] = 0;
	    }
	    else{
	        $_POST['goods_name'] 	= 	$CommonModel->getOne("SELECT goods_name FROM " . ' ybr_goods ' . " WHERE goods_id= '$_POST[goods_id]'");
	    }
	    
	    if (empty($_POST['start_price'])){
	        $_POST['start_price'] 	= 	0;
	    }
	    if (empty($_POST['end_price'])){
	        $_POST['end_price'] 	= 	0;
	    }
	    if (empty($_POST['max_price'])){
	        $_POST['max_price'] 	= 	0;
	    }
	    if (empty($_POST['cost_points'])){
	        $_POST['cost_points'] 	= 	0;
	    }
	    if (isset($_POST['product_id']) && empty($_POST['product_id'])){
	        $_POST['product_id'] 	= 	0;
	    }
	    
	    /* 检查活动重名 */
	    $sql 						= 	"SELECT COUNT(*) ".
	           							" FROM " . 'ybr_goods_activity'.
	           							" WHERE act_type='" . GAT_SNATCH . "' AND act_name='" . $_POST['snatch_name'] . "' AND act_id <> '" .  $_POST['id'] . "'" ;
	    if ($CommonModel->getOne($sql)){
	        //sys_msg(sprintf($_LANG['snatch_name_exist'],  $_POST['snatch_name']) , 1);
	        $this->error(sprintf( L('snatch_name_exist'),  $_POST['snatch_name']));
	    }
	
	    $info 					= 	array('start_price'=>$_POST['start_price'], 'end_price'=>$_POST['end_price'], 'max_price'=>$_POST['max_price'], 'cost_points'=>$_POST['cost_points']);
	
	    /* 更新数据 */
	    $record 				= 	array('act_name' => $_POST['snatch_name'], 'goods_id' => $_POST['goods_id'],
	                    			'goods_name' =>$_POST['goods_name'], 'start_time' => $_POST['start_time'],
	                    			'end_time' => $_POST['end_time'], 'act_desc' => $_POST['desc'],
				                    'product_id'=>$_POST['product_id'],
	        			            'ext_info'=>serialize($info));
	    $CommonModel->autoExecute('goods_activity', $record, 'UPDATE', "act_id = '" . $_POST['id'] . "' AND act_type = " . GAT_SNATCH );
			    
	    admin_log($_POST['snatch_name'],'edit','snatch');	// 记录操作
	    $this->success("编辑完成",U('snatch/snatch_list'));	    
	}
	
	
	/**
	 * 删除夺宝奇兵(抢购活动)
	 * Enter description here ...
	 */
	public function delete_snatch(){
		
		import("@.Plugs.Exchange");
		
	    $id 		= 	intval($_GET['id']);
	    $exc		=	new Exchange("ybr_goods_activity", null, 'act_id', 'act_name');	  
	    $exc->drop($id);
	    $this->success("操作成功",U('snatch/snatch_list'));
	}
	
	/**
	 * 搜索商品
	 * Enter description here ...
	 */
	public function search_goods(){
	
	    $filters 		= 	$_GET['JSON'];	
	    $arr['goods'] 	= 	get_goods_list($filters);
	    	
	    if (!empty($arr['goods'][0]['goods_id'])){
	        $arr['products'] 	= 	get_good_products($arr['goods'][0]['goods_id']);
	    }	
	    $return['content']	=	$arr;
		$return['error']	=	0;
		$return['message']	=	"";
		$this->ajaxReturn($return);
	}
	
	/**
	 * 搜索货品
	 * Enter description here ...
	 */
	public function search_products(){
		
	    $filters 			= 	$_GET['JSON'];
	    if (!empty($filters['goods_id'])){
	        $arr['products']= 	get_good_products($filters['goods_id']);
	    }	
	    $return['content']	=	$arr;
		$return['error']	=	0;
		$return['message']	=	"";
		$this->ajaxReturn($return);
	}
	
	
	
	
	
	
	
	
	
	
	
	
	
}



